<template>
  <div class="login-page">
    <h2 class="page-title">{{ $t('auth.login.title') }}</h2>
    
    <el-form
      ref="formRef"
      :model="loginForm"
      :rules="rules"
      label-position="top"
      size="large"
    >
      <el-form-item :label="$t('auth.login.email')" prop="email">
        <el-input
          v-model="loginForm.email"
          type="email"
          :placeholder="$t('auth.login.email')"
          prefix-icon="Message"
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.login.password')" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          :placeholder="$t('auth.login.password')"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      
      <el-form-item>
        <div class="form-options">
          <el-checkbox v-model="loginForm.remember">
            {{ $t('auth.login.remember') }}
          </el-checkbox>
          <router-link to="/auth/forgot-password" class="forgot-link">
            {{ $t('auth.login.forgot') }}
          </router-link>
        </div>
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          size="large"
          style="width: 100%"
          :loading="loading"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          {{ isSubmitting ? '登录中...' : $t('common.login') }}
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="auth-switch">
      <span>{{ $t('auth.login.noAccount') }}</span>
      <router-link to="/auth/register" class="switch-link">
        {{ $t('auth.login.goRegister') }}
      </router-link>
    </div>
    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { LocalStorage } from '@/utils/storage'
import type { LoginForm } from '@/types'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const loginForm = reactive<LoginForm>({
  email: '',
  password: '',
  remember: false
})

// 组件挂载后加载记住的邮箱
onMounted(() => {
  const rememberedEmail = LocalStorage.getRememberedEmail()
  const rememberLogin = LocalStorage.getRememberLogin()
  
  if (rememberedEmail) {
    loginForm.email = rememberedEmail
    loginForm.remember = rememberLogin
  }
})

// 表单验证规则
const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 防抖处理
const isSubmitting = ref(false)
let submitTimer: number | null = null

/**
 * 处理登录
 */
const handleSubmit = async () => {
  if (!formRef.value || isSubmitting.value) return
  
  // 防止重复提交
  if (submitTimer) {
    clearTimeout(submitTimer)
  }
  
  submitTimer = setTimeout(async () => {
    try {
      const valid = await formRef.value!.validate()
      if (!valid) return
      
      isSubmitting.value = true
      loading.value = true
      
      if (import.meta.env.DEV) {
        console.log('开始登录...')
      }
      
      const result = await userStore.login(loginForm)
      
      if (import.meta.env.DEV) {
        console.log('登录结果:', result)
      }
      
      if (result.success) {
        // 成功消息，2秒后自动关闭
        ElMessage({
          message: result.message,
          type: 'success',
          duration: 2000,
          showClose: true
        })
        
        // 获取重定向地址
        const redirect = route.query.redirect as string
        
        if (import.meta.env.DEV) {
          console.log('准备跳转到:', redirect || '/')
        }
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(async () => {
          try {
            if (redirect) {
              await router.push(redirect)
            } else {
              await router.push('/')
            }
            if (import.meta.env.DEV) {
              console.log('跳转成功')
            }
          } catch (error) {
            console.error('跳转失败:', error)
            // 如果跳转失败，尝试使用replace进行导航
            try {
              if (redirect) {
                await router.replace(redirect)
              } else {
                await router.replace('/')
              }
            } catch (replaceError) {
              console.error('替换导航也失败:', replaceError)
              // 最后的备选方案：使用router.go(0)刷新当前页面
              router.go(0)
            }
          }
        }, 500) // 500ms后跳转
        
      } else {
        // 错误消息，3秒后自动关闭
        ElMessage({
          message: result.message,
          type: 'error',
          duration: 3000,
          showClose: true
        })
      }
    } catch (error) {
      console.error('登录过程出错:', error)
      ElMessage({
        message: '登录失败，请重试',
        type: 'error',
        duration: 3000,
        showClose: true
      })
    } finally {
      loading.value = false
      // 延迟重置提交状态，防止快速重复点击
      setTimeout(() => {
        isSubmitting.value = false
      }, 1000)
    }
  }, 300) // 300ms防抖
}
</script>

<style lang="scss" scoped>
.login-page {
  .page-title {
    text-align: center;
    font-size: var(--font-size-2xl);
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: var(--spacing-2xl);
  }
  
  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .forgot-link {
      color: var(--primary-color);
      text-decoration: none;
      font-size: var(--font-size-sm);

      &:hover {
        color: var(--primary-dark);
        text-decoration: underline;
      }
    }
  }
  
  .auth-switch {
    text-align: center;
    margin-top: var(--spacing-lg);
    color: var(--text-secondary);
    
    .switch-link {
      color: var(--primary-color);
      text-decoration: none;
      margin-left: var(--spacing-xs);
      
      &:hover {
        color: var(--primary-dark);
      }
    }
  }
  
  .demo-tip {
    margin-top: var(--spacing-xl);
    
    :deep(.el-alert__content) {
      p {
        margin: var(--spacing-xs) 0;
        font-size: var(--font-size-sm);
      }
    }
  }
}
</style> 